<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-form-model
        layout="inline"
        :model="queryParam"
      >
        <a-row :gutter="15">
          <a-col :md="6" :sm="24">
            <a-form-model-item label="专利申请号">
              <a-input v-model="queryParam['filter[zl_no]']" placeholder="请输入专利申请号" />
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-model-item label="业务编号">
              <a-input v-model="queryParam['filter[business_no]']" placeholder="请输入业务编号" />
            </a-form-model-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="合同编号">
                <a-input v-model="queryParam['filter[contract_no]']" placeholder="请输入合同编号" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="所属顾问">
                <a-select
                  show-search
                  v-model="queryParam['filter[adviser_uid]']"
                  placeholder="输入要搜索的顾问姓名"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  @search="onSearch"
                >
                  <a-select-option v-for="(item,index) in searchSource" :key="index" :value="index">
                    {{ item }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="专利名称">
                <a-input v-model="queryParam['filter[zl_name]']" placeholder="请输入专利名称"/>
              </a-form-model-item>
            </a-col>
            <a-col v-if="group == 'small_leader'" :md="6" :sm="24">
              <a-form-model-item label="专利流程">
                <a-select v-model="queryParam['filter[receive_uid]']" placeholder="请选择专利流程">
                  <a-select-option v-for="(item,index) in processOpts" :key="index" :value="index">{{item}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="案件状态">
                <a-input type="text" v-model="queryParam['filter[state_name]']" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="专利老师">
                <a-select v-model="queryParam['filter[patenteer]']" placeholder="请选择专利老师">
                  <a-select-option v-for="(item,index) in patentOpts" :key="index" :value="index">{{item}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
                <span class='table-page-search-submitButtons' :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button type="primary" @click="$refs.table.refresh(true)">搜索</a-button>
                  <a-button style="margin-left: 8px" @click="resetForm">重置</a-button>
                  <a @click="toggleAdvanced" style="margin-left: 8px">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'" />
                  </a>
                </span>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <div class="table-operator">
      <s-table
        bordered
        size="middle"
        ref="table"
        :row-key="(record) => record.cb_id"
        :columns="infoColumns"
        :data="infoData"
      >
        <div slot="title">
          <a-button type="primary" size="small" @click="onImport">批量上传</a-button>
        </div>
        <div
          slot="filterDropdown"
          slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
          style="padding: 8px"
        >
          <a-input
            v-ant-ref="c => (searchInput = c)"
            :placeholder="`搜索${column.title}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block;"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
            @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          />
          <a-button
            type="primary"
            icon="search"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            搜索
          </a-button>
          <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
            重置
          </a-button>
        </div>
        <template slot="contract_no" slot-scope="text,record">
          {{text}}<br>
          {{record.business_no}}
        </template>
        <template slot="adviser" slot-scope="text,record">
          <a-tag>{{text}}</a-tag><br>
          <a-tag>{{record.group_type}}组</a-tag><br>
          <a-tag>{{record.leader}}</a-tag>
        </template>
        <template slot="state_name" slot-scope="text,record">
          <div v-if="text === ''">
            <a-tag color="red">{{record.status2}}</a-tag>
          </div>
          <div v-else>
            <a-tag color="red">[官方]{{text}}</a-tag>
          </div>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onEditNo(record.cb_id)">编辑</a-button>
          <a-button type="danger" size="small" @click="receiptModal(record.cb_id)">回执管理</a-button>
          <a-button type="default" size="small" @click="handleButtonClick(record.cb_id)">查看</a-button>
        </template>
      </s-table>
    </div>
    <a-modal
      centered
      v-model="receiptVisible"
      title="回执管理"
      :width="800"
      @ok="submitReceipt"
      @cancel="cancelReceipt"
    >
      <a-row :gutter="10">
        <a-col :span="16">
          <div style="margin-bottom: 20px;">历史回执记录</div>
          <a-timeline v-if="receiptHistory.length > 0">
            <a-timeline-item v-for="(item,index) in receiptHistory" :key="index">
              {{item.created_at}}  {{item.uid}}  添加回执【{{item.state_name}}】  <a :href="item.file">{{item.filename}}</a>  <a-button type="link" icon="delete" @click="delState(item.cbs_id)">删除</a-button>
            </a-timeline-item>
          </a-timeline>
        </a-col>
        <a-col :span="8">
          <a-form-model
            :model="receiptForm"
          >
            <a-form-model-item label="添加回执">
              <a-radio-group @change="onChangeStatus">
                <a-radio :style="radioStyle" v-for="(item, index) in receiptOpts" :key="index" :value="index">
                  {{item}}
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="上传文件">
              <a-upload
                name="file"
                :multiple="true"
                :headers="headers"
                :action="uploadUrl"
                :show-upload-list="false"
                @change="onChange"
              >
                <a-button size="small" icon="upload" type="primary">选择文件</a-button>
              </a-upload>
            </a-form-model-item>
            <a-button v-if="receiptForm.file != ''" type="link" size="small" icon="download" @click="download(receiptForm.filename, receiptForm.file)"><ellipsis :length="25">{{receiptForm.filename}}</ellipsis></a-button>
          </a-form-model>
        </a-col>
      </a-row>
    </a-modal>
    <a-modal
      centered
      title="编辑专利号"
      v-model="noVisible"
      :width="300"
      @ok="submitZlNo"
      @cancel="cancelReceipt"
    >
      <!--      <a-form-model-item label="专利名称">-->
      <!--        <a-input type="text" placeholder="请输入专利名称" />-->
      <!--      </a-form-model-item>-->
      <a-form-model
        :model="zlForm"
      >
        <a-form-model-item label="专利申请号" prop="zl_no">
          <a-input type="text" placeholder="请输入专利申请号" v-model="zlForm.zl_no"/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      title="批量导入回执"
      v-model="importVisible"
      :destroy-on-close="true"
      @ok="onSubmit"
    >
      <a-form-model
        ref="importForm"
        :model="importForm"
        :rules="importRules"
      >
        <a-form-model-item label="官方状态" prop="state_id">
          <a-select
            show-search
            v-model="importForm.state_id"
            placeholder="请选择业务分类"
            :filter-option="filterOption"
            @change="onSelect2"
          >
            <a-select-option v-for="(item,index) in stateOpts" :key="index" :value="index">{{item}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="上传回执压缩包" prop="filename">
          <a-upload
            name="file"
            accept=".zip"
            :headers="headers"
            :action="uploadUrl"
            @change="changeUpload"
          >
            <a-button type="danger" icon="upload" size="small">上传受通压缩包</a-button>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <batch-action v-if="settingsVisible"></batch-action>
  </div>
</template>

<script>
import apis from '@/api'
import storage from 'store'
import { ACCESS_TOKEN, GROUP, ROLE } from '@/store/mutation-types'
import BatchAction from '@/views/patent-process/components/BatchAction'
import { Ellipsis, STable } from '@/components'
import businessColumns from '@/columns/patent.process'
import {
  getGather,
  onCompletionAdviser,
  getReceiptHistory,
  getReceiptList,
  postReceiptList,
  getEditZlNo,
  postEditZlNo,
  delState,
  getImport,
  postImport
} from '@/api/patent.process'

export default {
  components: {
    BatchAction,
    STable,
    Ellipsis
  },
  name: 'States',
  data () {
    return {
      loading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      infoColumns: businessColumns.information,
      infoData: parameters => {
        return getGather(Object.assign(parameters, this.queryParam)).then(res => {
          this.patentOpts = res.result.patenteer_opts
          this.businessOpts = res.result.businesses
          this.processOpts = res.result.flow
          return res.result
        })
      },
      queryParam: {},
      advanced: true,
      receiptVisible: false,
      receiptForm: {},
      radioStyle: {
        display: 'block',
        height: '40px',
        lineHeight: '40px'
      },
      noVisible: false,
      searchSource: [],
      patentOpts: {},
      processOpts: {},
      receiptOpts: {},
      receiptHistory: {},
      uploadUrl: apis.Upload,
      headers: {
        'Access-Token': storage.get(ACCESS_TOKEN)
      },
      group: storage.get(GROUP),
      groupType: storage.get(ROLE),
      zlForm: {},
      editNoId: '',
      businessOpts: {},
      stateOpts: {},
      settingsVisible: false,
      importForm: {},
      importRules: {
        business_id: [{ required: true, message: '请选择业务分类', trigger: 'blur' }],
        state_id: [{ required: true, message: '请选官方状态', trigger: 'blur' }],
        filename: [{ required: true, message: '请上传受通压缩包', trigger: 'blur' }]
      },
      importVisible: false,
      searchInput: null,
      searchText: '',
      searchedColumn: ''
    }
  },
  methods: {
    receiptModal (id) {
      const app = this
      app.receiptForm = {}
      getReceiptList(id).then(res => {
        if (res.status === 0) {
          app.receiptOpts = res.result.state_opts
          app.receiptForm['cb_id'] = id
          app.receiptForm['file'] = 'xxx'
          app.receiptForm['filename'] = '无'
          app.getHistoryData(id)
          app.receiptVisible = true
        } else {
          app.$warning({
            title: res.msg
          })
          return false
        }
      })
    },
    getHistoryData (id) {
      const app = this
      getReceiptHistory(id).then(res => {
        if (res.status === 0) {
          app.receiptHistory = res.result.data
        } else {
          app.$warning({
            title: res.msg
          })
          return false
        }
      })
    },
    handleButtonClick (id) {
      if (this.groupType === 'proced_zl_engineer') {
        this.$router.push({ name: 'BusinessEdit', params: { id } })
      } else {
        this.$router.push({ name: 'AdminDetail', params: { id } })
      }
    },
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },
    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
    },
    submitReceipt () {
      const app = this
      const data = {}
      data['contract_business_state[file]'] = app.receiptForm.file
      data['contract_business_state[filename]'] = app.receiptForm.filename
      data['contract_business_state[state_id]'] = app.receiptForm.state_id
      postReceiptList(app.receiptForm['cb_id'], data).then(res => {
        if (res.status === 0) {
          app.receiptForm.file = 'xxx'
          app.receiptForm.filename = '无'
          app.getHistoryData(app.receiptForm['cb_id'])
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    cancelReceipt  () {
      this.$refs.table.refresh()
    },
    onChangeStatus (e) {
      this.receiptForm.state_id = e.target.value
    },
    onChange (info) {
      if (info.file.status === 'uploading') {
        return false
      }
      if (info.file.status === 'done') {
        this.receiptForm.filename = info.file.name
        this.receiptForm.file = info.file.response.result.url
        this.getHistoryData(this.receiptForm['cb_id'])
      }
    },
    download (name, url) {
      const downloadUrl = apis.Download
      const params = '?filename=' + name + '&value=' + url
      window.open(downloadUrl + params)
    },
    resetForm () {
      this.queryParam = {}
      this.$refs.table.refresh(true)
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    onEditNo (id) {
      const app = this
      getEditZlNo(id).then(res => {
        app.zlForm.zl_no = res.result.zl_no
        app.zlForm['id'] = id
        app.noVisible = true
      })
    },
    submitZlNo () {
      const app = this
      const data = {}
      data['zl_no'] = app.zlForm.zl_no
      postEditZlNo(app.zlForm.id, data).then(res => {
        if (res.status === 0) {
          app.noVisible = false
          app.cancelReceipt()
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    delState (id) {
      const app = this
      app.$confirm({
        title: '是否删除官方状态',
        onOk: () => {
          delState(id).then(res => {
            if (res.status === 0) {
              app.getHistoryData(app.receiptForm['cb_id'])
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        }
      })
    },
    onSearch (searchText) {
      onCompletionAdviser(searchText).then(res => {
        this.searchSource = res.result.data
      })
    },
    onImport () {
      this.importForm = {}
      getImport().then(res => {
        if (res.status === 0) {
          this.stateOpts = res.result.state_opts
          this.importVisible = true
        } else {
          this.$warning({
            title: res.msg
          })
        }
      })
    },
    onSetting () {
      this.settingsVisible = true
    },
    onSelect2 (key) {
      this.importForm['state_id'] = key
    },
    changeUpload (info) {
      if (info.file.status === 'uploading') {
        return false
      }
      if (info.file.status === 'done') {
        this.importForm['filename'] = info.file.name
        this.importForm['value'] = info.file.response.result.url
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    onSubmit () {
      const app = this
      const data = {}
      app.$refs.importForm.validate(valid => {
        if (valid) {
          data['file[filename]'] = app.importForm['filename']
          data['file[value]'] = app.importForm['value']
          // data['arr[business_id]'] = app.importForm['business_id']
          // data['arr[state_name]'] = app.importForm['state_name']
          data['arr[state_id]'] = app.importForm['state_id']
          postImport(data).then(res => {
            if (res.status === 0) {
              app.importVisible = false
              app.$refs.table.refresh()
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
